{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import datetime, date\n",
    "import pandas as pd\n",
    "from gs_quant.instrument import FXOption, FXForward\n",
    "from gs_quant.common import BuySell, OptionType, AggregationLevel\n",
    "from gs_quant.backtests.triggers import (\n",
    "    PeriodicTrigger,\n",
    "    PeriodicTriggerRequirements,\n",
    "    StrategyRiskTrigger,\n",
    "    RiskTriggerRequirements,\n",
    "    TriggerDirection,\n",
    ")\n",
    "from gs_quant.backtests.actions import AddTradeAction, HedgeAction\n",
    "from gs_quant.backtests.generic_engine import GenericEngine\n",
    "from gs_quant.backtests.strategy import Strategy\n",
    "from gs_quant.risk import Price, FXDelta"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize session\n",
    "from gs_quant.session import GsSession\n",
    "\n",
    "GsSession.use(client_id=None, client_secret=None, scopes=('run_analytics',))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Buy $100k 1y EURUSD ATMF call, roll monthly, delta hedge when breach of +50k"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define backtest dates\n",
    "start_date = date(2021, 6, 1)\n",
    "end_date = datetime.today().date()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define instrument for strategy\n",
    "\n",
    "# FX Option\n",
    "call = FXOption(\n",
    "    buy_sell=BuySell.Buy,\n",
    "    option_type=OptionType.Call,\n",
    "    pair='EURUSD',\n",
    "    strike_price='ATMF',\n",
    "    expiration_date='1y',\n",
    "    notional_amount=1e5,\n",
    "    name='1y_call',\n",
    "    premium=0,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Let's look at FX Delta for strategy without hedging\n",
    "\n",
    "# Define frequency for adding trade\n",
    "freq_add = '1m'\n",
    "trig_req = PeriodicTriggerRequirements(start_date=start_date, end_date=end_date, frequency=freq_add)\n",
    "action_add = AddTradeAction(call, freq_add)\n",
    "\n",
    "# Starting with empty portfolio (first arg to Strategy), apply actions in order on trig_req\n",
    "triggers = PeriodicTrigger(trig_req, action_add)\n",
    "strategy = Strategy(None, triggers)\n",
    "\n",
    "# Run backtest daily\n",
    "GE = GenericEngine()\n",
    "backtest = GE.run_backtest(\n",
    "    strategy,\n",
    "    start=start_date,\n",
    "    end=end_date,\n",
    "    frequency='1b',\n",
    "    show_progress=True,\n",
    "    risks=[Price, FXDelta(aggregation_level=AggregationLevel.Type, currency='USD')],\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View FX Delta risk\n",
    "b1 = pd.DataFrame(\n",
    "    {'No Hedge': backtest.result_summary[FXDelta(aggregation_level=AggregationLevel.Type, currency='USD')]}\n",
    ")\n",
    "b1.plot(figsize=(10, 6), title='FX Delta')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View results summary\n",
    "backtest.result_summary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Let's hedge delta when it is above +50k\n",
    "\n",
    "# Define frequency for adding trade\n",
    "freq_add = '1m'\n",
    "trig_req_add = PeriodicTriggerRequirements(start_date=start_date, end_date=end_date, frequency=freq_add)\n",
    "action_add = AddTradeAction(call, freq_add)\n",
    "trigger_add = PeriodicTrigger(trig_req_add, action_add)\n",
    "\n",
    "# Define risk to hedge\n",
    "hedge_risk = FXDelta(aggregation_level='Type', currency='USD')\n",
    "\n",
    "# Define FX Forward to hedge with\n",
    "fwd_hedge = FXForward(pair='EURUSD', settlement_date='1y', notional_amount=1e5, name='1y_forward')\n",
    "action_hedge = HedgeAction(hedge_risk, fwd_hedge)\n",
    "\n",
    "# Define hedge triggers\n",
    "trig_req_hedge = RiskTriggerRequirements(risk=hedge_risk, trigger_level=50e3, direction=TriggerDirection.ABOVE)\n",
    "trigger_risk = StrategyRiskTrigger(trig_req_hedge, action_hedge)\n",
    "\n",
    "# Starting with empty portfolio (first arg to Strategy), apply actions in order on trig_req\n",
    "strategy = Strategy(None, [trigger_add, trigger_risk])\n",
    "\n",
    "# Run backtest daily\n",
    "GE = GenericEngine()\n",
    "backtest = GE.run_backtest(strategy, start=start_date, end=end_date, frequency='1b', show_progress=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View FX Delta risk\n",
    "b2 = pd.DataFrame(\n",
    "    {'Hedge above +50k': backtest.result_summary[FXDelta(aggregation_level=AggregationLevel.Type, currency='USD')]}\n",
    ")\n",
    "b2.plot(figsize=(10, 6), title='FX Delta')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View backtest trade ledger\n",
    "backtest.trade_ledger()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Let's compare the two results\n",
    "b1.columns = ['No Hedge']\n",
    "b2.columns = ['Hedge above +50k']\n",
    "pd.concat([b1, b2], axis=1).plot(figsize=(10, 6))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}